import Vue from 'vue'
import VueRouter from 'vue-router'
import Home from '../views/Home.vue'

Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    redirect: '/home',
  },
  {
    path: '/home',
    name: 'Home',
    component: Home,
  },
  {
    path: '/goods',
    name: 'Goods',
    component: () => import(/* webpackChunkName: "about" */ '../views/Goods.vue'),
  },
  {
    path: '/user',
    name: 'User',
    component: () => import(/* webpackChunkName: "about" */ '../views/User.vue'),
    //重定向到/user/cart页面
    redirect:('/user/cart'),
    children: [
      { //子路由不加 / 斜杠
        path: 'cart',
        name: 'Cart',
        component: () => import(/* webpackChunkName: "about" */ '../components/User/Cart.vue'),
      },
    ],
  },
  {
    path: '/dingdan',
    name: 'Dingdan',
    component: () => import(/* webpackChunkName: "about" */ '../views/Dingdan.vue'),
  },
  {
    path: '/free',
    name: 'Free',
    component: () => import(/* webpackChunkName: "about" */ '../views/Free.vue'),
  },
  {
    path: '/details',
    name: 'Details',
    component: () => import(/* webpackChunkName: "about" */ '../views/Details.vue'),
  },
  { //当上面所有路由都匹配不上，就会加载此路由对应的组件
    path: '*',
    name: 'Error',
    component: () => import(/* webpackChunkName: "about" */ '../views/Error.vue'),
    
  }
]

const router = new VueRouter({
  routes,
  scrollBehavior(to, from, savedPosition) {
    // 始终滚动到顶部
    return { y : 0 }
  }
})

router.beforeEach((to, from, next) => {
  //访问/user时，判断token，有token跳转，没有就return
  if (to.path === '/user/cart') {
    //获取本地token
    let token = localStorage.getItem('x-auth-token')
    if (token) {
      //允许跳转
      next()
    } else {
      alert('请先登录')
    }
    return
  }
  //其他路径允许跳转，必须有一个next，否则任何路径都无法跳转
  next()
})

export default router
